<template>
  <div id="add">
    <!-- 头部 -->
    <div class="navebar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="工单编号">
          <el-input
            v-model="formInline.taskCode"
            placeholder="请输入工单编号"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="工单状态">
          <el-select
            v-model="formInline.status"
            placeholder="活动区域"
            style="width: 200px"
          >
            <el-option
              v-for="(item, index) in task"
              :key="index"
              :label="item.statusName"
              :value="item.statusId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit">
            查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="box">
      <div class="btn">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          class="btn1"
          @click="addtest"
        >新建</el-button>
        <el-button
          type="warning"
          plain
          class="btn2"
          @click="centerDialogVisible1 = true"
        >工单配置</el-button>
      </div>
      <div class="tabel">
        <el-table
          v-loading="loading"
          :data="SearchList"
          style="width: 100%"
          :header-cell-style="{
            //标题头部的颜色
            background: '#f5f7fa',
            height: '40px',
          }"
        >
          <el-table-column
            fixed
            type="index"
            label="序号"
            width="70"
            align="center"
          />
          <el-table-column
            prop="taskCode"
            label="工单编号"
            width="150"
            align="center"
          />
          <el-table-column
            prop="innerCode"
            label="设备编号"
            width="145"
            align="center"
          />
          <el-table-column
            prop="taskType.typeName"
            label="工单类型"
            width="140"
            align="center"
          />
          <el-table-column label="工单方式" width="140" align="center">
            <template #default="scope">
              {{ createType[scope.row.createType] || "未知" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="taskStatusTypeEntity.statusName"
            label="工单状态"
            width="140"
            align="center"
          />
          <el-table-column
            prop="userName"
            label="运营人员"
            width="170"
            align="center"
          />
          <el-table-column label="创建日期" width="200">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="handleClick(scope.row)"
              >查看详情</el-button>
              <!-- <el-button type="text" size="small">编辑</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <!-- 实现分页
        current-page 当前页数
        page-size 每页显示个数
        total 总条目数
        current-change 页面改变时会触发
         -->
        <div class="block">
          <el-pagination
            background
            :current-page.sync="pageOption.pageIndex"
            :page-size="pageOption.pagesize"
            layout="total, pager,prev, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
        <!-- 查看详情组件 -->
        <lookOf :details="ViewDetails" :task="taskData" @newClick="newClickFn" @close="close" @delWork="delWork" />
      </div>
    </div>

    <!-- 新增工单弹出框 -->
    <div class="addWork">
      <el-dialog
        title="新增工单"
        :visible.sync="centerDialogVisible"
        width="45%"
        @close="closeFn"
      >
        <!-- 表单内容 -->
        <el-form
          ref="departRef"
          :model="departForm"
          :rules="departRules"
          label-width="120px"
        >
          <el-form-item label="设备编号" prop="innerCode">
            <el-input
              v-model="departForm.innerCode"
              style="width: 85%"
              placeholder="请输入编号"
              @input="test"
            />
          </el-form-item>
          <el-form-item label="工单类型" prop="taskType">
            <el-select
              v-model="departForm.taskType"
              style="width: 85%"
              placeholder="请选择"
            >
              <el-option
                v-for="item in taskSty"
                :key="item.id"
                :label="item.typeName"
                :value="item.trpeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="补货数量">

            <!-- 补货工单弹出框激活 -->
            <span style="color: #5f84ff" @click="ReplenishmentFn">
              <i class="el-icon-document" />
              <a href="javascript:void(0)">补货工单</a>
            </span>
          </el-form-item>
          <el-form-item label="运营人员" prop="assignorId">
            <el-select
              v-model="departForm.assignorId"
              style="width: 85%"
              placeholder="请选择"
            >
              <el-option
                v-for="item in managerList"
                :key="item.id"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="desc">
            <el-input
              v-model="departForm.desc"
              style="width: 85%"
              placeholder="请输入备注（不超过40字）"
              type="textarea"
            />
          </el-form-item>
        </el-form>
        <!-- 底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button
            class="btnquxiao"
            @click="closeFn"
          >取 消</el-button>
          <el-button
            type="primary"
            class="btn1"
            @click="submitWork"
          >确 定</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- 工单配置弹窗 -->
    <el-dialog
      title="工单配置"
      :visible.sync="centerDialogVisible1"
      width="50%"
      center
    >
      <!-- 表单内容 -->
      <el-form>
        <el-form-item label="补货警戒线">
          <el-input-number v-model="num" controls-position="right" :min="1" :max="60" />
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button
          class="btnquxiao"
          @click="centerDialogVisible1 = false"
        >取 消</el-button>
        <el-button
          type="primary"
          class="btn1"
          @click="centerDialogVisible1 = false"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 补货工单弹出框 -->
    <el-dialog
      title="补货详情"
      :visible.sync="Replenishment"
      width="45%"
      center
    >
      <!-- 中间表格内容 -->
      <template>
        <el-table :data="channelList" height="400" style="width: 100%">
          <el-table-column prop="channelCode" label="货道编号" width="100" />
          <el-table-column prop="sku.skuName" label="商品名称" width="100" />
          <el-table-column
            prop="currentCapacity"
            label="当前数量"
            width="100"
          />
          <el-table-column prop="maxCapacity" label="还可添加" width="100" />
          <el-table-column prop="city" label="补满数量" width="200">
            <template slot-scope="{ row }">
              <el-input-number
                v-if="row.sku.skuName!=='-'"
                v-model="row.number2"
                controls-position="right"
                :min="row.min"
                :max="row.max"
              />
              <span v-else>货道暂无商品</span>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button
          class="btnquxiao"
          @click="Replenishment = false"
        >取 消</el-button>
        <el-button
          type="primary"
          class="btn1"
          @click="addlist"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import Tabel from './compounts/tabeList.vue'
import {
  taskstateApi,
  // allTaskApi,
  createdApi,
  getTaskApi,
  searchstateApi,
  operatorListApi,
  getChannelListApi,
  delWorkApi
} from '@/api'
import { Message } from 'element-ui'
import lookOf from './compounts/lookof.vue'
import dayjs from 'dayjs'
export default {
  components: {
    // Tabel
    lookOf
  },
  data() {
    return {
      loading: false,
      // 添加弹出框
      centerDialogVisible: false,
      centerDialogVisible1: false,
      ViewDetails: false, // 查看详情弹框
      Replenishment: false, // 补货工单
      // 工单配置
      num: 60,
      // 搜索框
      formInline: {
        taskCode: '',
        status: ''
      },
      // 新建表单数据
      departForm: {
        innerCode: '', // 设备编号
        taskType: '', // 工单类型
        assignorId: '', // 运营人员
        desc: '' // 备注
      },
      // 表单校验
      departRules: {
        innerCode: [{ required: true, message: '设备编号不能为空', trigger: ['blur'] }],
        // taskType: [{ required: true, message: '工单类型不能为空', trigger: ['blur'] }],
        assignorId: [{ required: true, message: '请选择运营人员', trigger: ['blur'] }],
        desc: [{ required: true, message: '备注不能为空', trigger: ['blur'] }]
      },
      task: [], // 工单状态
      taskSty: [{ type: 2, typeId: 2, typeName: '补货工单' }], // 工单类型
      SearchList: [], // 工单列表
      managerList: [], // 运营人员
      list: [],
      channelList: [], // 补货工单表格
      details: [], // 处理后补货清单列表
      taskData: {},
      // 表格内容
      createType: {
        1: '手动',
        2: '自动'
      },
      // 搜索传入的数值
      pageOption: {
        pageIndex: 1,
        pagesize: 10,
        isRepair: false // 是否是维修工单
      },
      pageOptions: {},
      currentPage1: 4,
      total: 0
    }
  },
  async created() {
    this.loading = true
    try {
      // 工单状态列表
      // 工单类型
      // 工单搜索
      // 运营工单
      const res = await taskstateApi()
      this.task = res.data
      this.loading = false
      this.getSearchstateApi()
      // const { data } = await operatorListApi(this.departForm.innerCode)
      // console.log(data)
      // this.managerList = data
    } catch (error) {
      this.loading = false
    }
  },
  methods: {
    // 工单搜索封装
    async getSearchstateApi() {
      const { data } = await searchstateApi(this.pageOption)
      console.log(data)
      this.SearchList = data.currentPageRecords
      this.total = +data.totalCount
    },

    // 查询功能
    // 绑定查询事件，在下面声明点击事件
    // 封装数据请求接口、引入、使用
    // 点击查询按钮，将数据传给子组件表格
    // 子组件接收，并进行数据请求实现查询功能
    onSubmit() {
      console.log('submit!')
      console.log(this.pageOption)
      this.pageOption = { ...this.pageOption, ...this.formInline }
      console.log(this.pageOption)
      this.getSearchstateApi(this.pageOption)
    },

    // 新建工单
    // 注册新建按钮的点击事件
    // 准备弹窗的dom结构
    // 对弹窗内的输入框注册表单校验
    // 封装接口，引入接口
    // 声明点击事件
    // 点击新建按钮，开启弹窗
    // 输入设备编号，在输入框失焦之后请求运营人员的数据
    async addtest() {
      this.centerDialogVisible = true
    },
    async test() {
      // this.$refs.departRef.validate(async(vaild) => {
      //   if (!vaild) return
      console.log(11)
      // this.centerDialogVisible = true
      console.log(this.departForm.innerCode)
      const { data } = await operatorListApi(this.departForm.innerCode)
      console.log(data)
      this.managerList = data
      // })
    },

    // 补货工单
    // 准备补货工单弹窗dom结构
    // 封装数据请求接口
    // 绑定 补货工单按钮事件点击开启补货工单弹窗
    // 引入数据请求接口并在弹窗开启时调用
    async ReplenishmentFn() {
      if (!this.departForm.innerCode) return Message.warning('请填入设备编号')
      const { data } = await getChannelListApi(this.departForm.innerCode)
      data.forEach(item => {
        if (item.maxCapacity - item.currentCapacity <= 0) {
          this.$set(item, 'number', 0)
          this.$set(item, 'number2', 0)
          this.$set(item, 'min', 0)
          this.$set(item, 'max', 0)
        } else {
          this.$set(item, 'number', item.maxCapacity - item.currentCapacity)
          this.$set(item, 'number2', item.maxCapacity - item.currentCapacity)
          this.$set(item, 'min', 0)
          this.$set(item, 'max', item.maxCapacity - item.currentCapacity)
        }
        if (item.sku === null) {
          this.$set(item, 'number', '-')
          item.sku = {}
          this.$set(item, 'currentCapacity', '-')
          this.$set(item.sku, 'skuName', '-')
        }
      })
      this.channelList = data
      this.Replenishment = true
      console.log(data)
    },

    // 补货清单确认
    addlist() {
      this.channelList.forEach(item => {
        if (item.sku !== '-') {
          this.details.push({
            channelCode: item.channelCode,
            expectCapacity: item.number2,
            skuId: item.sku.skuId,
            skuImage: item.sku.skuImage,
            skuName: item.sku.skuName
          })
        }
      })
      console.log(this.details)
      this.Replenishment = false
    },

    // 新增工单提交事件
    // 首先处理清单信息
    // 点击确定进行兜底校验
    // 请求接口，传入数据
    // 提示用户、关闭弹窗、清空表单
    async submitWork() {
      this.$refs.departRef.validate(async(vaild) => {
        if (!vaild) return
        await createdApi({
          ...this.departForm,
          details: this.details, // 清单信息
          createType: 1, // 创建类型，传1
          userId: 1// 执行人Id
        })
        Message.success('工单添加成功')
        this.centerDialogVisible = false
        this.getSearchstateApi()
        this.departForm = {
          innerCode: '',
          taskType: '',
          assignorId: '',
          desc: ''
        }
      })
    },

    // 点击取消关闭弹窗、清除表单
    closeFn() {
      this.centerDialogVisible = false
      this.$refs.departRef.resetFields()
      this.departForm = {
        innerCode: '', // 设备编号
        taskType: '', // 工单类型
        assignorId: '', // 运营人员
        desc: '' // 备注
      }
    },

    // 点击查看详情
    // 展示查看详情的弹窗组件
    // 请求数据
    // 将数据传给子组件查看详情弹窗
    async handleClick(row) {
      this.ViewDetails = true
      console.log(row)
      const { data } = await getTaskApi(row.taskId)
      console.log(data)
      this.taskData = data
    },

    // 格式化时间
    formatDate(value) {
      return dayjs(value).format('YYYY-MM-DD hh:mm:ss')
    },

    // 在查看详情弹窗里的重新创建按钮上注册新建弹窗弹出事件
    // 声明事件
    // 封装数据请求接口、引入、使用
    // 点击重新创建
    // 关闭查看详情页面,新建弹窗弹出
    // 数据回显功能
    // 引入数据请求接口并使用
    // 在打开的新建弹窗李实现数据回显,
    async newClickFn(val) {
      console.log(val)
      this.ViewDetails = false
      this.centerDialogVisible = true
      const { data } = await getTaskApi(val)
      console.log(data)
      this.departForm = data
    },
    close() {
      this.ViewDetails = false
    },
    // 实现分页
    handleCurrentChange(val) {
      this.loading = true
      this.getSearchstateApi()
      this.pageOption.pageIndex = val
      this.loading = false
      console.log(`当前页: ${val}`)
    },

    // 取消工单
    // 在子组件绑定自定义事件
    // 封装取消工单接口
    // 声明自定义事件
    // 引入取消工单接口
    // 在子组件声明取消工单事件、传入id给父组件
    // 同事父组件调用接口删除工单
    // 提示用户取消成功
    // 调用请求数据方法重新渲染表格
    // 优化表格分页
    delWork(val) {
      this.$confirm('此操作将永久取消该工单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delWorkApi({
          taskId: val.taskId,
          desc: val.desc
        })
        Message.success('该工单已成功取消')
        if (this.SearchList.length === 1 && this.pageOption.pageIndex > 1) {
          this.pageOption.pageIndex--
        }
        this.getSearchstateApi()
      })
    },
    handleChange() {},
    handleChangeFn(value) {
      console.log(value)
    }
  }
}
</script>

<style lang="scss">
#add {
  overflow: hidden;
  background-color: #f8fafd;
}
.navebar {
  margin: 20px 19px 0;
  padding-top: 14px;
  padding-left: 18px;
  height: 64px;
  background-color: #fff;
}
// 表格
.box {
  margin: 20px 19px 0;
  padding: 17px 0 1px 18px;
  background-color: #fff;
}
// 按钮
.btn1 {
  background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
  border: #f8fafd;
  height: 35px;
}
// 详情弹出框
.title{
  margin-top: -20px;
  margin-bottom: 30px;
  color: #393939;
}
.title img{
  position: absolute;
  top: 53px;
  left: 433px;
}
.el-alert--info.is-light {
  color: #040404;
}
.el-alert{
  padding: 13px 16px;
}
// 表格高度
.el-table .el-table__cell {
    padding: 3px 0 0 0;
}
// 内容
.el-descriptions{
  padding: 0px 0px 0px 30px;
}
.addWork .el-dialog__footer {
  margin-top: -55px;
  padding: 15px 205px;
}
.dialog-footer{
  margin-top: 10px;
  display: flex;
  margin-left: 13px;
}
.btnquxiao {
  margin-right: 10px;
  height: 37px;
}
.btn2 {
  background-color: #fbf4f0;
  border: #f8fafd;
  color: #f97138;
  height: 35px;
}
.button{
  background-color: #fbf4f0;
  border: #f8fafd;
  color: #f97138;
}
// 分页器
.block{
  margin: 20px 0;
}
.tabel {
  margin-top: 19px;
}
</style>
